package com.ruoyi.system.service.module.wx.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.wx.WxMessage;
import com.ruoyi.system.domain.module.*;
import com.ruoyi.system.domain.module.estate.EstateUser;
import com.ruoyi.system.domain.module.estate.RepairRecord;
import com.ruoyi.system.domain.module.property.PropertyFeeOrder;
import com.ruoyi.system.domain.module.wx.*;
import com.ruoyi.system.mapper.module.*;
import com.ruoyi.system.mapper.module.wx.UserMpMapper;
import com.ruoyi.system.mapper.module.wx.WxTemplateMapper;
import com.ruoyi.system.mapper.module.wx.WxUserMapper;
import com.ruoyi.system.service.module.*;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.system.service.module.wx.IWxTemplateService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号的模板消息列Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Service
public class WxTemplateServiceImpl extends ServiceImpl<WxTemplateMapper, WxTemplate> implements IWxTemplateService {

	@Resource
	private UserMpMapper userMpMapper;
	@Resource
	private WxTemplateMapper wxTemplateMapper;
	@Resource
	private WxUserMapper wxUserMapper;
	@Resource
	private IEstateUserService estateUserService;
	@Resource
	private IParameterService parameterService;

	@Value("${web.appid}")
	private String appid;//小程序appid
	@Value("${web.secret}")
	private String secret;//小程序appid
	@Value("${web.appidMp}")
	private String appidMp;//公众号appid
	@Value("${web.secretMp}")
	private String secretMp;//公众号secret

	@Override
	@Transactional
	public String getAccessToken(int type) {
		String access_token = "";
		try{
			Parameter parameter = parameterService.findById(1);
			if(type == 0){//公众号
				access_token = parameter.getAccessTokenMp();
				if(new Date().getTime() > parameter.getAcMpLastTime().getTime()){
					access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
					parameter.setAccessTokenMp(access_token);
					//记录2小时之后的时间s
					parameter.setAcMpLastTime(DateUtils.getAfterSecondsByOld(new Date(),7200));
					parameterService.updateById(parameter);
				}
			}else{//小程序
				access_token = parameter.getAccessToken();
				if(new Date().getTime() > parameter.getAcLastTime().getTime()) {
					access_token = WxMessage.getACCESSTOKEN(appid, secret);
					parameter.setAccessToken(access_token);
					parameter.setAcLastTime(DateUtils.getAfterSecondsByOld(new Date(),7200));
					parameterService.updateById(parameter);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return access_token;
	}

	/**
	 * 订单支付成功 公众号推送消息
	 * @param user
	 * @param feeOrder
	 * @return
	 */
	@Override
	public int sendWxMsgByPropertyFee(WxUser user, PropertyFeeOrder feeOrder) {
		try{
//			String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);

//			String accessToken = redisTemplate.opsForValue().get("access_token_mp") !=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//			if(StrUtil.isEmpty(accessToken)){
//				accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//				redisTemplate.opsForValue().set("access_token_mp",accessToken,3600L, TimeUnit.SECONDS);
//			}
			String access_token = getAccessToken(0);//WxMessage.getACCESSTOKEN(appidMp,secretMp);

			QueryWrapper<UserMp> qw = new QueryWrapper<>();
			qw.eq("union_id",user.getUnionId());
			qw.last("limit 1");
			UserMp userMp = userMpMapper.selectOne(qw);
			if(userMp!=null){
				WxMsgTemplate template = getTemplateToUser(userMp,feeOrder,19);
				String param = JSONUtil.parseObj(template).toString();
				System.out.println("公众号推送消息 - 用户端请求信息:" + param);
				JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
				System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
				return 1;
			}
			return 0;
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  发送推送消息到 商家管理员微信上
	 * @param userMp
	 * @param feeOrder
	 * @param template_type   10  物业费用通知
	 * @return
	 */
	private WxMsgTemplate getTemplateToUser(UserMp userMp, PropertyFeeOrder feeOrder, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniProgram = new HashMap<>();
			miniProgram.put("appid",appid);
			miniProgram.put("pagepath","pagesProperty/pages/propertyList/index?state=0");
			template.setMiniprogram(miniProgram);

			Map<String, MsgTempData> m = new HashMap<>();

//			物业费：10元
//			代收水费：10元
//			代收电费：10元
//			垃圾处理费：10元
//			交费时间段：2022-3月~2022-3月
//			感谢您的关注与使用，具体详情，请点击查看进行操作。
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的业主您好，我们根据您的申请，已生成物业•费用清单");
			m.put("first",first);

			//物业费
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(feeOrder.getWyfFee()+"元");
			m.put("keyword1",keyword1);

			//代收水费
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(feeOrder.getElectricFee()+ "元");
			m.put("keyword2",keyword2);

			//代收电费
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(feeOrder.getWaterFee()+ "元");
			m.put("keyword3",keyword3);

			//垃圾处理费
			MsgTempData keyword4 = new MsgTempData();
			keyword4.setColor(wxTemplate.getFontColor());
			keyword4.setValue(feeOrder.getTrashFee()+ "元");
			m.put("keyword4",keyword4);

			//交费时间段
			MsgTempData keyword5 = new MsgTempData();
			keyword5.setColor(wxTemplate.getFontColor());
			String date =  DateUtils.getYearMonthTime(feeOrder.getBeginTime())
				+ "~" + DateUtils.getYearMonthTime(feeOrder.getEndTime());
			keyword5.setValue(date);
			m.put("keyword5",keyword5);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
//			feeOrder.getEstateName() + " " + feeOrder.getRoomNo()
			remark.setValue("申请地址：" +feeOrder.getRoomNo() + "，感谢您的关注与使用，订单详情，请点击查看。");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}

	/**
	 *  报修指派成功 公众号推送消息
	 * @param repairRecord
	 * @param template_type
	 * @return
	 */
	@Override
	public int sendWxMsgRepair(RepairRecord repairRecord, Integer template_type){
		try{
//			String access_token = redisTemplate.opsForValue().get("access_token_mp")!=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//			if(StrUtil.isEmpty(access_token)){
//				access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//				redisTemplate.opsForValue().set("access_token_mp",access_token,3600L, TimeUnit.SECONDS);
//			}
			String access_token = getAccessToken(0);//WxMessage.getACCESSTOKEN(appidMp,secretMp);

			QueryWrapper<EstateUser> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("estate_id",repairRecord.getEstateId());
			qw.eq("state",1);
			List<EstateUser> list = estateUserService.list(qw);
			if(CollUtil.isNotEmpty(list)){
				for (EstateUser estateUser : list){
					WxUser user1 = wxUserMapper.selectById(estateUser.getUserId());
					if(user1!=null){
						UserMp userMp = userMpMapper.selectOneByColumn("union_id",user1.getUnionId());
						if(userMp!=null){
							WxMsgTemplate template = getRepairTemplateToManager(userMp,repairRecord,17);
							String param = JSONUtil.parseObj(template).toString();
							JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
							System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
						}
					}
				}
			}

//			QueryWrapper<EstateUser> qwWorker = new QueryWrapper<>();
//			//财务部门
//			qwWorker.eq("estate_id",repairRecord.getEstateId());
//			qwWorker.eq("user_type", 3);
//			qwWorker.eq("state",1);
//			List<EstateUser> workers = estateUserService.list(qwWorker);
//			if(CollUtil.isNotEmpty(workers)){
//				for (EstateUser worker : workers){
//					WxUser user1 = wxUserMapper.selectById(worker.getUserId());
//					if(user1 != null){
//						UserMp userMp = userMpMapper.selectOneByColumn("union_id",user1.getUnionId());
//						if(userMp!=null){
//							WxMsgTemplate template = getRepairTemplateToManager(userMp,repairRecord,17);
//							String param = JSONUtil.parseObj(template).toString();
//							JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
//							System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
//						}
//					}
//				}
//			}
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  发送推送消息到 管理员微信上
	 * @param userMp
	 * @param repairRecord
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getRepairTemplateToManager(UserMp userMp, RepairRecord repairRecord, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		if(wxTemplate!=null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesProperty/pages/repairInfo/index?id=" +repairRecord.getId());
			template.setMiniprogram(miniprogram);

			Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
//			{{first.DATA}}
//			工单编号：{{keyword1.DATA}}
//			报修位置：{{keyword2.DATA}}
//			报修内容：{{keyword3.DATA}}
//			维修服务人员：{{keyword4.DATA}}
//			报修类型：{{keyword5.DATA}}
//			{{remark.DATA}}
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的小区管理员，报修任务已派发，请悉知并关注跟进");
			m.put("first",first);

			//工单编号
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(repairRecord.getRecordNo());
			m.put("keyword1",keyword1);

			//报修位置
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(repairRecord.getEstateName() +  repairRecord.getRoomNo());
			m.put("keyword2",keyword2);

			//报修内容
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(repairRecord.getContent());
			m.put("keyword3",keyword3);

			//维修服务人员
			MsgTempData keyword4 = new MsgTempData();
			keyword4.setColor(wxTemplate.getFontColor());
			keyword4.setValue(repairRecord.getOpUserName());
			m.put("keyword4",keyword4);

			//报修类型
			MsgTempData keyword5 = new MsgTempData();
			keyword5.setColor(wxTemplate.getFontColor());
			if(repairRecord.getCheckType() == 0){
				keyword5.setValue("屋外报修");
			}else{
				keyword5.setValue("屋内报修");
			}
			m.put("keyword5",keyword5);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			remark.setValue("该工单已安排"+repairRecord.getOpUserName() + "进行处理，请及时跟进。感谢您对本工作的支持与付出。");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}

}
